<template>
  <DynamicList
    ref="eventActivityListTable"
    v-bind="eventActivityListColumns"
    @load-data="setPage"
    @reset-data="onResetData"
  >
    <template #tableTop>
      <a-space class="flex-wrap" size="small">
        <a-button
          v-if="$auth('event-activity-add')"
          type="primary"
          @click="router.push('/eventActivity/eventActivityAdd')"
        >
          <PlusOutlined />
          新增
        </a-button>
      </a-space>
    </template>
    <template #searchQuery>
      <div>
        <span class="pr-8px">事件/活动类型：</span>
        <a-select
          v-model:value="queryData.type"
          class="min-w-150px"
          allow-clear
          :options="typeList"
          placeholder="请选择事件/活动类型"
        ></a-select>
      </div>
      <div class="inline-flex items-center">
        <span class="pr-8px">活动开始时间：</span>
        <a-range-picker
          v-model:value="startDate"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('startDate', dateString)"
        />
      </div>
      <div>
        <span class="pr-8px">活动结束时间：</span>
        <a-range-picker
          v-model:value="endDate"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('endDate', dateString)"
        />
      </div>
    </template>
  </DynamicList>
</template>

<script setup lang="tsx">
  import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { message, Modal } from 'ant-design-vue';
  import type { Dayjs } from 'dayjs';
  import { deleteEventActivity, enabledActivity, eventActivityApi } from '@/api/eventActivity';
  import { formatToDateTime } from '@/utils/dateUtil';
  import DynamicList from '@/components/dynamicList/index.vue';
  import { RequestEnum } from '@/enums/httpEnum';
  import useRequestList from '@/hooks/useRequestList';
  import { verifyAuth } from '@/core/permission';
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import { useUserStore } from '@/store/modules/user';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { publishOptions, StatusEnum } from '@/enums/DisableEnum';
  import { categoryJsonByType } from '@/api/category';
  import { categoryTypeEnum } from '@/enums/categoryTypeEnum';

  const userStore = useUserStore();
  const rusticId = userStore.getRusticId();

  const valueFormat = 'YYYY-MM-DD HH:mm';
  const eventActivityListTable = ref<any>(null);
  const typeList = ref<{ id: number; name: string }[]>([]);
  const router = useRouter();

  type RangeValue = [Dayjs, Dayjs];
  interface QueryDataParams {
    startEndTime: string;
    startStartTime: string;
    endEndTime: string;
    endStartTime: string;
    type: number | null;
  }
  const endDate = ref<RangeValue | string[]>();
  const startDate = ref<RangeValue | string[]>();
  const queryData = reactive<QueryDataParams>({
    endEndTime: '',
    endStartTime: '',
    startEndTime: '',
    startStartTime: '',
    type: null,
  });

  const { list, page, setPage, loading } = useRequestList({
    apiKey: eventActivityApi.eventActivityList,
    type: RequestEnum.GET,
    initParam: {
      rusticId,
    },
  });
  const eventActivityListColumns = ref({
    columns: [
      {
        title: '序号',
        width: 30,
        align: 'center',
        dataIndex: 'index',
        fixed: 'left',
        customRender: ({ record, text, index }) => index + 1,
      },
      {
        title: '封面',
        width: 60,
        align: 'center',
        fixed: 'left',
        dataIndex: 'cover',
        customRender: ({ text }) => {
          return text ? <a-image width="80px" src={getFileHttpUrl(text)} /> : '-';
        },
      },
      {
        title: '事件/活动',
        width: 80,
        align: 'center',
        fixed: 'left',
        dataIndex: 'name',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '地址',
        width: 60,
        align: 'center',
        dataIndex: 'address',
      },
      {
        title: '事件/活动类型',
        width: 80,
        align: 'center',
        dataIndex: 'typeName',
      },
      {
        title: '活动开始时间',
        width: 80,
        align: 'center',
        dataIndex: 'startTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '活动结束时间',
        width: 80,
        align: 'center',
        dataIndex: 'endTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '发布时间',
        width: 60,
        align: 'center',
        dataIndex: 'publishTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '排序',
        width: 50,
        align: 'center',
        dataIndex: 'sort',
      },
      // {
      //   title: '更新时间',
      //   width: 50,
      //   align: 'center',
      //   dataIndex: 'updateTime',
      //   customRender: ({ text }) => {
      //     return text ? formatToDateTime(text) : '-';
      //   },
      // },
      {
        title: '创建时间',
        width: 60,
        align: 'center',
        dataIndex: 'createTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '状态',
        width: 80,
        align: 'center',
        fixed: 'right',
        dataIndex: 'status',
        search: true,
        component: ComponentsTypeEnum.Select,
        componentProps: {
          options: publishOptions,
        },
        customRender: ({ record }) => {
          return (
            <a-switch
              onChange={() => updateStatus(record)}
              v-model:checked={record.status}
              un-checked-value={StatusEnum.DISABLED}
              checked-value={StatusEnum.NORMAL}
              un-checked-children={'已下架'}
              checked-children={'已发布'}
            />
          );
        },
      },
      {
        title: '操作',
        width: 100,
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
        actions: [
          {
            title: '详情',
            vIf: verifyAuth('event-activity-detailPage'),
            onClick: (record) => {
              router.push(`/eventActivity/eventActivityDetail?id=${record.id}`);
            },
          },
          {
            title: '编辑',
            vIf: verifyAuth('event-activity-update'),
            onClick: (record) => {
              router.push(`/eventActivity/eventActivityEdit?id=${record.id}`);
            },
          },
          {
            title: '删除',
            vIf: verifyAuth('event-activity-delete'),
            onClick: (record) => {
              deleteConfirmEventActivity(record);
            },
          },
        ],
      },
    ],
    queryParamsSlots: queryData,
    pageParams: page,
    list,
    loading,
    columnProps: {
      scroll: {
        x: 'calc(100vw - 220px)',
      },
      bordered: true,
    },
  });

  const deleteConfirmEventActivity = async (record) => {
    Modal.confirm({
      title: '确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        const res = await deleteEventActivity({ id: record.id });
        if (res) {
          message.success(res?.msg);
          eventActivityListTable.value && eventActivityListTable.value.resetFields();
        }
      },
    });
  };
  const onResetData = (queryParams: Object) => {
    for (const queryParamsKey in queryData) {
      queryData[queryParamsKey] = null;
    }
    endDate.value = [queryData.endStartTime, queryData.endEndTime];
    startDate.value = [queryData.startStartTime, queryData.startEndTime];
    setPage(queryParams);
  };

  const onRangeChange = (type: string, dateString: string[]) => {
    if (type === 'startDate') {
      queryData.startStartTime = dateString[0];
      queryData.endStartTime = dateString[1];
    } else {
      queryData.startEndTime = dateString[0];
      queryData.endEndTime = dateString[1];
    }
  };

  const updateStatus = async (record: { id: number }) => {
    const res = await enabledActivity({ id: record.id });
    if (res) {
      message.success(res?.msg);
      eventActivityListTable.value && eventActivityListTable.value.resetFields();
    }
  };

  const getCategoryList = async () => {
    const res = await categoryJsonByType({ type: categoryTypeEnum.ACTIVITY });
    if (res) {
      typeList.value = res.data.map((item: { name: string; id: number }) => ({
        label: item.name,
        value: item.id,
      }));
      // typeMap = new Map(typeList.value.map((value, key) => [key, value]));
      // console.info('typeMap ==> ', typeMap);
    }
    // return typeMap;
  };

  onMounted(() => {
    getCategoryList();
  });
</script>

<style></style>
